package com.zf.thread_pool.thread_first;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 自定义拒绝策略: 先尝试加入工作队列，如果不能加入，就由提交任务的线程执行
 */
public class CustomThreadFirstRejectedPolicy implements RejectedExecutionHandler {
    private static final Logger log = LoggerFactory.getLogger(CustomThreadFirstRejectedPolicy.class);

    private final RejectedExecutionHandler delegateRejectHandler;

    public CustomThreadFirstRejectedPolicy() {
        delegateRejectHandler = new ThreadPoolExecutor.CallerRunsPolicy();
    }

    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        boolean offer = false;
        // 尝试加入工作队列
        try {
            offer = executor.getQueue().offer(r, 0, TimeUnit.SECONDS);
        } catch (InterruptedException ignored) {
        }
        // 如果加入失败，执行拒绝策略，由提交任务的线程执行该任务
        if (!offer) {
            delegateRejectHandler.rejectedExecution(r, executor);
        }
    }
}